﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Deployment.Application;
using System.IO;

namespace D3StatsClient.Logging
{
    public class Logger
    {
        private static String _currentLogFile;
        private static readonly int _logFileExpirationTime = 30; //in Minutes
        private static readonly long _logFileMaxFileSize = 300720; // In bytes (30 megs)
        private static readonly Logger _instance;
        private static readonly String _logPath;

        static Logger()
        {
            try
            {
                _instance = new Logger();

                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    _logPath = ApplicationDeployment.CurrentDeployment.DataDirectory + "\\Logs";
                }
                else
                {
                    _logPath = "c:\\dev\\logs";
                }

                _instance.CreateLogFile();
            }
            catch { }
        }

        internal static string LogFilePath
        {
            get
            {
                return _currentLogFile;
            }
        }

        /// <summary>
        /// Creates a new log file.
        /// </summary>
        private void CreateLogFile()
        {
            try
            {
                //Create the log directory if it doesn't exist.
                if (!Directory.Exists(_logPath))
                {
                    Directory.CreateDirectory(_logPath);
                }

                _currentLogFile = _logPath + "\\" + BuildLogFileName();

                File.Create(_currentLogFile).Close();

            }
            catch
            {
            }

        }

        private static String BuildLogFileName()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("d3tracker_log_");
            builder.Append(DateTime.Now.Day.ToString() + "_");
            builder.Append(DateTime.Now.Month.ToString() + "_");
            builder.Append(DateTime.Now.Year.ToString() + "_");
            builder.Append(DateTime.Now.Millisecond.ToString());
            builder.Append(".txt");

            return builder.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <param name="level"></param>
        public static void Log(String message)
        {

            try
            {
                _instance.WriteLogEntry(_instance.GetTimestamp() + " :: " + message);
            }
            catch
            {
            }
        }

        private void CheckCurrentLogFileExpiration()
        {
            if (File.Exists(_currentLogFile))
            {
                FileInfo info = new FileInfo(_currentLogFile);
                DateTime creationTime = info.CreationTime;
                DateTime expirationTime = creationTime.AddMinutes(_logFileExpirationTime);


                if ((DateTime.Compare(DateTime.Now, expirationTime) > 0) || (info.Length > _logFileMaxFileSize))
                {
                    //We need a new log file created.
                    CreateLogFile();
                }
            }
            else
            {
                //No log file exist, we need to create one.
                CreateLogFile();
            }
        }

        /// <summary>
        /// Write the log entry to the log file.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="level"></param>
        private void WriteLogEntry(String value)
        {

            try
            {
                this.CheckCurrentLogFileExpiration();

                if (File.Exists(_currentLogFile))
                {
                    using (TextWriter tw = TextWriter.Synchronized(File.AppendText(_currentLogFile)))
                    {
                        tw.WriteLine(value);
                    }
                }
            }
            catch
            {
            }

        }

        /// <summary>
        /// Returns the current datetime.
        /// </summary>
        /// <returns></returns>
        private String GetTimestamp()
        {
            return DateTime.Now.ToLongTimeString();
        }

    }
}
